import type { IButtonMenu, IDomEditor } from "@wangeditor/editor";
import { useDialog } from "@/components/cl-dialog";
let editorInstance: IDomEditor;
let selectionText: string;
let selection: any;

export const { register, methods } = useDialog({
  height: 100,
  isFooter: false,
  // showClose: false,
  // modal: false,
  closeOnPressEscape: true,
  onClose() {
    if (!selectionText) return;

    /** 选区开始索引，包括此索引 */
    const selectStartIndex = selection!.anchor.offset;
    /** 选区结束索引，不包括此索引 */
    const selectEndIndex = selection!.focus.offset;

    editorInstance.select(selection);
    editorInstance.dangerouslyInsertHtml(
      `<span style="color:red;">${selectionText}</span>`
    );
    console.log("ok", editorInstance.dangerouslyInsertHtml);

    methods.value.setVisible(false);
    // selectionText = "";
  },
});

export const annotationText = ref("");

class Annotations implements IButtonMenu {
  title: string;
  tag: string;
  constructor() {
    this.title = "批注";
    this.tag = "button";
  }

  // 获取菜单执行时的 value ，用不到则返回空 字符串或 false
  getValue(editor: IDomEditor): string | boolean {
    return editor.getSelectionText();
  }

  // 菜单是否需要激活（如选中加粗文本，“加粗”菜单会激活），用不到则返回 false
  isActive(_editor: IDomEditor): boolean {
    return false;
  }

  // 菜单是否需要禁用（如选中 H1 ，“引用”菜单被禁用），用不到则返回 false
  isDisabled(_editor: IDomEditor): boolean {
    return false;
  }

  // 点击菜单时触发的函数
  exec(editor: IDomEditor, _value: string | boolean) {
    methods.value.setVisible(true);
    if (!editorInstance) {
      editorInstance = editor;
    }
    selectionText = editor.getSelectionText();
    selection = editor.selection;
    console.log({
      editor,
      select: editor.getSelectionText(),
      html: editor.getHtml(),
      position: editor.getSelectionPosition(),
      selection: editor.selection?.anchor.offset,
    });

    // editor.insertText(value); // value 即 this.value(editor) 的返回值
  }
}

export const annotationsConf = {
  key: "annotations", // 定义 menu key ：要保证唯一、不重复（重要）
  factory() {
    return new Annotations();
  },
};
